package it.cqupt.web.controller.store;

import com.github.pagehelper.PageInfo;
import it.cqupt.domain.store.QuestionItem;
import it.cqupt.utils.BeanUtil;
import it.cqupt.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/store/questionItem")
public class QuestionItemServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");
        if("list".equals(operation)){
            this.list(req,resp);
        }else if("save".equals(operation)){
            this.save(req,resp);
        }else if("delete".equals(operation)){
            this.delete(req,resp);
        }else if("toEdit".equals(operation)){
            this.toEdit(req,resp);
        }else if("edit".equals(operation)){
            this.edit(req,resp);
        }
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        QuestionItem questionItem = BeanUtil.fillBean(req, QuestionItem.class);
        questionItemService.update(questionItem);
        this.list(req,resp);
    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        QuestionItem item = questionItemService.findById(id);
        req.setAttribute("questionItem",item);
        req.setAttribute("operation","edit");
        list(req,resp);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        QuestionItem questionItem = BeanUtil.fillBean(req, QuestionItem.class);
        questionItemService.delete(questionItem);
        this.list(req,resp);
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        QuestionItem questionItem = BeanUtil.fillBean(req, QuestionItem.class);
        questionItemService.save(questionItem);
        this.list(req,resp);
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PageInfo all = questionItemService.findAll(1, 100,req.getParameter("questionId"));
        if(req.getParameter("operation") .length()==0){
            req.setAttribute("operation","save");
        }
        req.setAttribute("questionId",req.getParameter("questionId"));
        req.setAttribute("page",all);
        req.getRequestDispatcher("/WEB-INF/pages/store/questionItem/list1.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
